<?php

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Validator;
//与微信交互用
class WeChatController extends Controller
{
    public $appid;
    public $secret;

    //评价模板消息标题
    public $comment_title = '业务评价提醒';
    //评价模板消息id
    public $comment_id = '5kLaJpmxlnn3X2i0pYiG2xaz-pGssk-uPFE_5bSVFI4';
    //结账评价模板消息副标题
    public $settle_title = '御顺金融诚邀您进行结账评价';
    //上门评价模板消息副标题
    public $visit_title = '御顺金融诚邀您进行到访评价';
    //放款成功模板消息标题
    public $loan_title = '放款成功通知';
    //放款成功模板消息id
    public $loan_id = 'NoTOgYiZ_Xelz8wgQsU1YVG_yf_9_uzvBo9rw9XDhmw';
    //预约成功模板消息标题
    public $reservation_title = '预约成功通知';
    //预约成功模板消息id
    public $reservation_id = 'ZnmjJ-qaih39XIAX6bnL9SoO67OdpUeHOBgzv7DJIA8';

    //菜单【商务合作需要返回的图片id】
    public $MediaId = '_s3NtjX0JKYV9bMNez3LnLMhSfdX2eWNtIH-tcFYW8FXmFQM1m1l2hQcTKePVSAc';

    public $menu = [
        'button' => [
            [
                'name'  =>  '贷款助手',
                'sub_button' => [
                    [
                        'name'  =>  '贷款进度查询',
                        'type'  =>  'view',
                        'url'   =>  'http://jinbeih5.scyushun.com'
                    ],
                    [
                        'name' => '贷款额度计算器',
                        'type' => 'view',
                        'url' => 'http://wap.cdyushun.com/wx/quota/Calculator.html'
                    ],
                    [
                        'name' => '贷款知识点这里',
                        'type' => 'view',
                        'url' => 'https://mp.weixin.qq.com/mp/homepage?__biz=MzI5NzM5MTU3OQ==&hid=5&sn=c2e350d569afbcf97110ae354f35a4d4&scene=18'
                    ]
                ]
            ],
            [
                'name'  =>  '明星产品',
                'sub_button' => [
                    [
                        'name' => '3厘信用贷款',
                        'type' => 'view',
                        'url' => 'http://wap.cdyushun.com/wx/190612/gongxindai/'
                    ],
                    [
                        'name' => '贷1万·利息1块',
                        'type' => 'view',
                        'url' => 'http://wap.cdyushun.com/wx/190612/qiyedai/'
                    ],
                    [
                        'name' => '当天抵押贷款',
                        'type' => 'view',
                        'url' => 'http://wap.cdyushun.com/wx/190612/fangdidai/'
                    ]
                ]
            ],
            [
                'name'  =>  '找款姐',
                'sub_button' => [
                    [
                        'name'  =>  '我的现金券',
                        'type'  =>  'view',
                        'url'   =>  'http://55895196-bigwheel2.m.weimob.com/55895196/59300?channel=menu&sionid=a96407af931243b6b8fd6104488072cb'
                    ],
                    [
                        'name' => '联系款姐',
                        'type' => 'click',
                        'key'  => 'contact'
                    ],
                    [
                        'name' => '款姐公司',
                        'type' => 'view',
                        'url' => 'http://www.gpimg.cn/360/slja425jg224oge8_0823/?from=timeline&isappinstalled=0'
                    ],
                    [
                        //图片推送
                        /*'type'  =>  'click',
                        'key' =>  'cooperation',*/
                        'type'  => 'view',
                        'url'   => 'http://weixintest.kuanjiedai.com/images/hezuo.jpg',
                        'name'  =>  '商务合作'
                    ],
                    [
                        'name' => '个人中心',
                        'type' => 'view',
                        'url' => 'https://jinbeih5.scyushun.com'
                    ]
                    /*[
                        //陈龙辉测试用
                        'type'  =>  'view',
                        'url' =>  'https://jinbeih5.scyushun.com',
                        'name'  =>  '测试菜单'
                    ]*/
                ]

            ]
        ]
    ];


    /**
     * @param Request $request
     * @param $appid
     * @return mixed
     */
    public function index(Request $request,$appid){
        $app_info = DB::table('APPS')->where('appid',$appid)->first();

        if(!$app_info){
            return 'no app data in database';
        }

        $log_file = base_path() . '/storage/logs/'.$appid.'.log';
        $xml_str = file_get_contents('php://input');
        $log_str = "\r\n\r\n" . date('Y-m-d H:i:s') . " 接收的xml数据：" . $xml_str . "\r\n";

        error_log($log_str, 3, $log_file);

        $login_url = env('LOGIN_URL');
        if ($request->isMethod('post')) {//微信post方式推送xml消息
            if ($xml_str) {
                $data_from_wechat = xml_to_array($xml_str);

                error_log(date('Y-m-d H:i:s') . '  $data_from_wechat：' . print_r($data_from_wechat, 1) . "\r\n", 3, $log_file);

                $open_id = $data_from_wechat['FromUserName'];

                //事件消息
                if($data_from_wechat['MsgType'] == 'event'){//事件推送
                    if($data_from_wechat['Event'] == 'subscribe'){//关注
                        //用户未关注时，进行关注后的事件推送,EventKey是以qrscene_开头
                        if(isset($data_from_wechat['EventKey']) && strpos($data_from_wechat['EventKey'],'qrscene_') !== false){//扫描带参数二维码之后关注
                            //金贝的推送绑定信息
                            //提取扫描参数
                            $query = substr($data_from_wechat['EventKey'],8);

                            error_log(date('Y-m-d H:i:s') . '  $query：' . print_r($query, 1) . "\r\n", 3, $log_file);

                            $query = explode('|',$query);

                            $channel = $query[0];   //渠道
                            $area = $query[1] ?? '';  //公司网点
                            $manager_id = $query[2] ?? '';    //服务经理id
                            $manager_name = $query[3] ?? '';  //服务经理姓名
                            if($channel == 'self'){//扫描公司员工二维码时
                                $href = '<a href="'.$login_url.'/#/login?channel='.$channel.'&area='.$area.'&manager_id='.$manager_id.'&manager_name='.$manager_name.'">绑定</a>';
                                $post_str = '您好，服务经理-' . $manager_name . '为您服务，点击'.$href.'可将此经理设为您的专属顾问，享受贷款专业服务。';
                                //给用户发送消息
                                $post_xml = '<xml>
                                      <ToUserName><![CDATA[' . $open_id . ']]></ToUserName>
                                      <FromUserName><![CDATA[' . $app_info->dev_wechat . ']]></FromUserName>
                                      <CreateTime>' . time() . '</CreateTime>
                                      <MsgType><![CDATA[text]]></MsgType>
                                      <Content><![CDATA[' . $post_str . ']]></Content>
                                    </xml>';
                                error_log(date('Y-m-d H:i:s') . "扫描服务经理二维码关注后响应xml数据：" . $post_xml . "\r\n", 3, $log_file);
                            }else{//扫描其他渠道二维码时，渠道关注人数加1

                                exit("success");

                                /*DB::table('CHANNELS')->where('channel_id',$channel)->increment('accumulate_sub_num');
                                //$channel_id = DB::table('CHANNELS')->where('channel_name',$channel)->value('channel_id');

                                DB::table('CHANNEL_USERS')->updateOrInsert([
                                    'openid'=>$open_id,'dev_wechat'=>$data_from_wechat['ToUserName']],
                                    ['channel_id'=>$channel,'sub_time'=> date('Y-m-d H:i:s')]
                                );
                                $href = '<a href="'.$login_url.'/#/login?channel='.$channel.'">登录</a>';
                                $post_str = '您好，点击'.$href.'可享受贷款专业服务。';
                                //给用户发送消息
                                $post_xml = '<xml>
                                      <ToUserName><![CDATA[' . $open_id . ']]></ToUserName>
                                      <FromUserName><![CDATA[' . $app_info->dev_wechat . ']]></FromUserName>
                                      <CreateTime>' . time() . '</CreateTime>
                                      <MsgType><![CDATA[text]]></MsgType>
                                      <Content><![CDATA[' . $post_str . ']]></Content>
                                    </xml>';
                                error_log(date('Y-m-d H:i:s') . "扫描渠道二维码关注后响应xml数据：" . $post_xml . "\r\n", 3, $log_file);*/
                            }

                            exit($post_xml);
                        }else{//常规关注
                            exit("success");

                            /*$post_str = "/:,@-D好看的你，都关注款姐了\r\n我24小时在线哦\r\n贷款疑问，随时解答\r\n两小时快速解决资金周转问题<a href='http://wap.cdyushun.com/wx/190612/gongxindai/'>点我办理</a>\r\n贷款进度查询——><a href='".$login_url."'>点这里</a>";

                            error_log(date('Y-m-d H:i:s') . "  常规关注时响应string数据：" . $post_str . "\r\n", 3, $log_file);

                            $post_xml = '<xml>
                                          <ToUserName><![CDATA[' . $open_id . ']]></ToUserName>
                                          <FromUserName><![CDATA[' . $app_info->dev_wechat . ']]></FromUserName>
                                          <CreateTime>' . time() . '</CreateTime>
                                          <MsgType><![CDATA[text]]></MsgType>
                                          <Content><![CDATA[' . $post_str . ']]></Content>
                                        </xml>';

                            error_log(date('Y-m-d H:i:s') . "  常规关注时响应xml数据：" . $post_xml . "\r\n", 3, $log_file);

                            exit($post_xml);*/
                        }                        
                    }
                    if($data_from_wechat['Event'] == 'unsubscribe'){//取消关注
                        //如果是渠道用户，更新取关时间
                        $channel_id = DB::table('CHANNEL_USERS')->where('openid',$open_id)->value('channel_id');
                        if($channel_id){
                            DB::table('CHANNELS')->where('channel_id',$channel_id)->increment('accumulate_unsub_num');
                            DB::table('CHANNEL_USERS')->where([
                                'openid'=>$data_from_wechat['FromUserName'],
                                'dev_wechat'=>$data_from_wechat['ToUserName']
                            ])->update([
                                'unsub_time'=> date('Y-m-d H:i:s')
                            ]);
                        }
                    }
                    //关注后扫描带参数二维码
                    if($data_from_wechat['Event'] == 'SCAN'){
                        error_log(date('Y-m-d H:i:s') . "二维码参数：" . $data_from_wechat['EventKey'] . "\r\n", 3, $log_file);
                        $query = explode('|',$data_from_wechat['EventKey']);

                        $channel = $query[0];   //渠道
                        $area = $query[1] ?? '';
                        $manager_id = $query[2] ?? '';
                        $manager_name = $query[3] ?? '';

                        if($channel == 'self'){
                            $href = '<a href="'.$login_url.'/#/login?channel='.$channel.'&area='.$area.'&manager_id='.$manager_id.'&manager_name='.$manager_name.'">绑定</a>';
                            $post_str = '您好，服务经理-' . $manager_name . '为您服务，点击'.$href.'可将此经理设为您的专属顾问，享受贷款专业服务。';
                            //给用户发送消息
                            $post_xml = '<xml>
                                      <ToUserName><![CDATA[' . $open_id . ']]></ToUserName>
                                      <FromUserName><![CDATA[' . $app_info->dev_wechat . ']]></FromUserName>
                                      <CreateTime>' . time() . '</CreateTime>
                                      <MsgType><![CDATA[text]]></MsgType>
                                      <Content><![CDATA[' . $post_str . ']]></Content>
                                    </xml>';

                            error_log(date('Y-m-d H:i:s') . "关注后扫描服务经理二维码响应xml数据：" . $post_xml . "\r\n", 3, $log_file);

                            exit($post_xml);
                        }else{
                            exit("success");

                            /*//渠道的扫描数加1
                            DB::table('CHANNELS')->where('channel_id',$channel)->increment('scan_num');
                            $href = '<a href="'.$login_url.'/#/login?channel='.$channel.'">登录</a>';
                            $post_str = '您好，点击'.$href.'可享受贷款专业服务。';
                            //给用户发送消息
                            $post_xml = '<xml>
                                      <ToUserName><![CDATA[' . $open_id . ']]></ToUserName>
                                      <FromUserName><![CDATA[' . $app_info->dev_wechat . ']]></FromUserName>
                                      <CreateTime>' . time() . '</CreateTime>
                                      <MsgType><![CDATA[text]]></MsgType>
                                      <Content><![CDATA[' . $post_str . ']]></Content>
                                    </xml>';

                            error_log(date('Y-m-d H:i:s') . "关注后扫描渠道二维码响应xml数据：" . $post_xml . "\r\n", 3, $log_file);*/

                            exit($post_xml);
                        }
                    }

                    //点击自定义菜单中【商务合作】时回复一张图片
                    if($data_from_wechat['Event'] == 'CLICK' && $data_from_wechat['EventKey'] == 'cooperation'){
                        $open_id = $data_from_wechat['FromUserName'];

                        //给用户发送消息
                        $post_xml = '<xml>
                                      <ToUserName><![CDATA[' . $open_id . ']]></ToUserName>
                                      <FromUserName><![CDATA[' . $app_info->dev_wechat . ']]></FromUserName>
                                      <CreateTime>' . time() . '</CreateTime>
                                      <MsgType><![CDATA[image]]></MsgType>
                                      <Image>
                                         <MediaId><![CDATA['.$this->MediaId.']]></MediaId>
                                      </Image>                                 
                                    </xml>';

                        error_log(date('Y-m-d H:i:s') . "响应xml数据：" . $post_xml . "\r\n", 3, $log_file);

                        echo $post_xml;
                        exit;
                    }

                    //点击自定义菜单中【联系款姐】时回复
                    if($data_from_wechat['Event'] == 'CLICK' && $data_from_wechat['EventKey'] == 'contact'){
                        $open_id = $data_from_wechat['FromUserName'];

                        $post_str = "/:,@-D通话两分钟，贷款50万。\r\n\r\n款姐的电话：028-6666 1168\r\n款姐的微信：kuanjie_520";
                        //给用户发送消息
                        $post_xml = '<xml>
                                      <ToUserName><![CDATA[' . $open_id . ']]></ToUserName>
                                      <FromUserName><![CDATA[' . $app_info->dev_wechat . ']]></FromUserName>
                                      <CreateTime>' . time() . '</CreateTime>
                                      <MsgType><![CDATA[text]]></MsgType>
                                      <Content><![CDATA[' . $post_str . ']]></Content>
                                    </xml>';

                        error_log(date('Y-m-d H:i:s') . "响应xml数据：" . $post_xml . "\r\n", 3, $log_file);

                        echo $post_xml;
                        exit;
                    }

                    //模板消息推送事件通知
                    if($data_from_wechat['Event'] == 'TEMPLATESENDJOBFINISH'){
                        switch ($data_from_wechat['Status']){
                            case 'success':
                                $send_status = 1;
                                break;
                            case 'failed:user block':
                                $send_status = 3;
                                break;
                            case 'failed: system failed':
                                $send_status = 4;
                                break;
                        }
                        DB::table('TEMPLATE_MSGS')->where('msgid',$data_from_wechat['MsgID'])
                            ->update(['send_status'=>$send_status,'send_time'=>date('Y-m-d H:i:s')]);
                    }
                }

                //普通消息  文本消息
                if($data_from_wechat['MsgType'] == 'text'){
                    //exit('success');
                    $res_xml = $this->keyword_res($data_from_wechat,$appid);

                    error_log(date('Y-m-d H:i:s') . '  $res_xml：' . $res_xml . "\r\n", 3, $log_file);

                    exit($res_xml);
                }
            } else {
                error_log(date('Y-m-d H:i:s') . "no xml_str\r\n", 3, $log_file);
            }
        } elseif ($request->isMethod('get')) {//微信get方式请求，服务器接入时验证用
            $verify_data = $request->all();
            if ($verify_data) {
                $signature = $verify_data['signature'] ?? '';
                $timestamp = $verify_data['timestamp'] ?? '';
                $nonce = $verify_data['nonce'] ?? '';
                $echostr = $verify_data['echostr'] ?? '';

                if ($signature && $timestamp && $nonce && $echostr) {
                    $array = array($app_info->token, $timestamp, $nonce);
                    sort($array, SORT_STRING);
                    $str = implode($array);
                    $encry_str = sha1($str);

                    if ($encry_str == $signature) {
                        exit($echostr);
                    } else {
                        exit('encry check failed');
                    }
                }
            }
        }
    }

    /**
     * @param $appid
     * @return mixed
     */
    function get_access_token($appid){
        $log_file = base_path() . '/storage/logs/'.$appid.'.log';
        if(!$secret = DB::table('APPS')->where('appid',$appid)->value('app_secret')){
            return false;
        }
        if(Redis::exists('access_token_' . $appid)){
            $access_token = Redis::get('access_token_' . $appid);

            error_log(date('Y-m-d H:i:s') . ' redis取access_token:' . $access_token . "\r\n",3,$log_file);

            return $access_token;
        }else{
            $url = "https://Api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $client = new Client();
            $res = $client->get($url)->getBody()->getContents();
            $res = json_decode($res,1);

            error_log(date('Y-m-d H:i:s') . ' 生成access_token结果:' . print_r($res,1) . "\r\n",3,$log_file);
            error_log(date('Y-m-d H:i:s') . ' 生成access_token:' . $res['access_token'] . "\r\n",3,$log_file);

            Redis::setex('access_token_' . $appid,3600,$res['access_token']);

            return $res['access_token'];
        }
    }



    /**创建菜单
     * @param $appid
     */
    function create_menu($appid){
        $url = "https://Api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $this->get_access_token($appid);

        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->menu,JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_POST,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);

        // 3. 执行并获结果
        $output = curl_exec($ch);
        if($output === FALSE ){
            echo "CURL Error:".curl_error($ch);
        }
        // 4. 释放curl句柄
        curl_close($ch);

        dd($output);
    }

    //服务经理带参数二维码
    function show_manager_qr(Request $request){
        $appid = $request['appid'];
        $log_file = base_path() . '/storage/logs/'.$appid.'.log';
        $area = $request['area'];
        $manager_id = $request['manager_id'];
        $manager_name = $request['manager_name'];
        //渠道
        $channel = $request['channel'] ?? 'self';
        //二维码图片保存文件名
        $store_file = '/images/qr/' . $area . '_' . $manager_id .'.jpg';
        $qr_file = public_path() . $store_file;

        if(!is_file($qr_file)){
            $url = 'https://Api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $this->get_access_token($appid);
            $post_data = [
                "action_name" => "QR_LIMIT_STR_SCENE",
                "action_info" => [
                    "scene" => [
                        "scene_str" => "$channel|$area|$manager_id|$manager_name"
                    ]
                ]
            ];

		    error_log(date('Y-m-d H:i:s'). '生成带参数二维码参数：' . print_r($post_data,1) . "\r\n",3,$log_file);

            $res = curl_post($url,$post_data,'json');

            $res = json_decode($res,1);

            error_log(date('Y-m-d H:i:s'). '生成带参数二维码结果：' . print_r($res,1) . "\r\n",3,$log_file);

            $ticket = $res['ticket'];

            $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);

            $qr_res = curl_get($url);

            //将生成的二维码保存到本地
            file_put_contents(public_path() . $store_file,$qr_res);
        }

        $data = ['qr_url'=>config('app.url') . $store_file];

        return ['code'=>200,'data'=>$data];
    }

    //渠道二维码
    function channel_qr(Request $request){
        $appid = $request['appid'];
        $channel = $request['channel'];
        $log_file = base_path() . '/storage/logs/'.$appid.'.log';

        //二维码图片保存文件名
        $store_file = '/images/qr/' . $channel.'.jpg';
        $qr_file = public_path() . $store_file;

        if(!is_file($qr_file)){
            $url = 'https://Api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $this->get_access_token($appid);
            $post_data = [
                "action_name" => "QR_LIMIT_STR_SCENE",
                "action_info" => [
                    "scene" => [
                        "scene_str" => "$channel"
                    ]
                ]
            ];

            error_log(date('Y-m-d H:i:s'). '生成渠道二维码参数：' . print_r($post_data,1) . "\r\n",3,$log_file);

            $res = curl_post($url,$post_data,'json');

            $res = json_decode($res,1);

            error_log(date('Y-m-d H:i:s'). '生成渠道二维码结果：' . print_r($res,1) . "\r\n",3,$log_file);

            $ticket = $res['ticket'];

            $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);

            $qr_res = curl_get($url);

            //将生成的二维码保存到本地
            file_put_contents(public_path() . $store_file,$qr_res);
        }

        $data = ['qr_url'=>config('app.url') . $store_file];

        return ['code'=>200,'data'=>$data];
    }

    /**接收模板消息
     * @param Request $request open_id   username    created_at  type
     * @return array
     */
    public function receive_temp_msg(Request $request){
        $log_file = base_path() . '/storage/logs/'.$request->post('appid').'.log';
        error_log(date('Y-m-d H:i:s') . ' ' . print_r($request->all(),1) . "\n",3,$log_file);

        $insert_data = [
            'id' => null,
            'appid' => $request->post('appid'),
            'open_id' => $request->post('open_id'),
            'template_id' => $request->post('template_id'),
            'url' => $request->post('url'),
            'phone' => $request->post('phone'),
            'data' => json_encode($request->post('data'))
        ];

        if(DB::table('TEMPLATE_MSGS')->insert($insert_data)){
            return ['code'=>200,'message'=>'ok','data'=>null];
        }else{
            return ['code'=>500,'message'=>'插入数据库失败','data'=>null];
        }
    }
    
    //关键字回复
    function keyword_res($param,$appid) {
        //用户发送的信息入库
        DB::table('USER_MSGS')->insert([
            'msg' => $param['Content'],
            'open_id' => $param['FromUserName'],
            'dev_wechat' => $param['ToUserName']
        ]);
        $keyword = $param['Content'];
     
        $response_set = DB::table('KEYWORDS AS K')
                            ->leftJoin('KEYWORDS_TYPE_RECORDS AS KTR','K.ktr_id','=','KTR.ktr_id')
                            ->where([['K.appid','=',$appid],['KTR.status','=','1']])
                            ->where(function ($query) use ($keyword){
                                $query->where('keyword',$keyword)
                                    ->orWhere('keyword','like',$keyword . '|%')
                                    ->orWhere('keyword','like','%|' . $keyword)
                                    ->orWhere('keyword','like','%|' . $keyword . '|%');
                            })
                            ->first();
        
        if($response_set){
            switch ($response_set->type){
                case 'text' :   //文字
                    return '<xml>
                      <ToUserName><![CDATA[' . $param['FromUserName'] . ']]></ToUserName>
                      <FromUserName><![CDATA[' . $param['ToUserName'] . ']]></FromUserName>
                      <CreateTime>' . time() . '</CreateTime>
                      <MsgType><![CDATA[text]]></MsgType>
                      <Content><![CDATA['.$response_set->content.']]></Content>
                    </xml>';
                    break;
                case 'image' ://图片
                    return '<xml>
                              <ToUserName><![CDATA['.$param['FromUserName'].']]></ToUserName>
                              <FromUserName><![CDATA['.$param['ToUserName'].']]></FromUserName>
                              <CreateTime>'.time().'</CreateTime>
                              <MsgType><![CDATA[image]]></MsgType>
                              <Image>
                                <MediaId><![CDATA['.$response_set->media_id.']]></MediaId>
                              </Image>
                            </xml>';
                    break;
                case 'news' : //图文
                    return '<xml>
                              <ToUserName><![CDATA['.$param['FromUserName'].']]></ToUserName>
                              <FromUserName><![CDATA['.$param['ToUserName'].']]></FromUserName>
                              <CreateTime>'.time().'</CreateTime>
                              <MsgType><![CDATA[news]]></MsgType>
                              <ArticleCount>1</ArticleCount>
                              <Articles>
                                <item>
                                  <Title><![CDATA['.$response_set->title.']]></Title>
                                  <Description><![CDATA['.$response_set->description.']]></Description>
                                  <PicUrl><![CDATA['.$response_set->pic_url.']]></PicUrl>
                                  <Url><![CDATA['.$response_set->url.']]></Url>
                                </item>
                              </Articles>
                            </xml>';
                    break;
                default :
                    return 'success';
            }
        }else{
            //未设置关键字回复时转发客服消息
            return '<xml>
                      <ToUserName><![CDATA[' . $param['FromUserName'] . ']]></ToUserName>
                      <FromUserName><![CDATA[' . $param['ToUserName'] . ']]></FromUserName>
                      <CreateTime>' . time() . '</CreateTime>
                      <MsgType><![CDATA[transfer_customer_service]]></MsgType>              
                    </xml>';
            //return 'success';
        }
    }


    //微信网页授权获取用户信息
    function wechat_user_info(Request $request){
        $validate = Validator::make($request->all(),[
            'appid' => 'required','code'=>'required'
        ]);
        if($validate->fails()){
            return ['code' => 400,'message' => $validate->errors()->first()];
        }

        $secret = DB::table('APPS')->where('appid',$request['appid'])->value('app_secret');
        if(!$secret){
            return ['code' => 404,'message' => '公众号secret缺失'];
        }

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$request['appid'].'&secret='.$secret.'&code='.$request['code'].'&grant_type=authorization_code';
        $access_token_result = curl_get($url);

        $access_token_result = json_decode($access_token_result,1);

        if(isset($access_token_result['errcode'])){
            return ['code'=>$access_token_result['errcode'],'message'=>$access_token_result['errmsg']];
        }

        $log_file = base_path() . '/storage/logs/'.$request->post('appid').'.log';

        error_log(date('Y-m-d H:i:s') .  ' 微信网页授权获取access_token:' . $access_token_result['access_token'],3,$log_file);

        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token_result['access_token'].'&openid='.$access_token_result['openid'].'&lang=zh_CN';

        $res = curl_get($url);

        $res = json_decode($res,1);

        if(isset($res['errcode'])){
            return ['code' => $res['errcode'], 'message' => $res['errmsg']];
        }
        $res = ['code' => 200,'data' => $res];
        return $res;
    }


    function sign(){
        return view('sign');
    }

    //微信js-sdk接入时生成签名,暂未使用。
    function wechat_js_sign(Request $request){
        $log_file = base_path() . '/storage/logs/'.$request->post('appid').'.log';

        $ticket = $this->get_jsapi_ticket($request['appid']);
        if($ticket){
            $noncestr = random_str();
            $time = time();
            $str = 'jsapi_ticket='.$ticket.'&noncestr='.$noncestr.'&timestamp=' . $time . '&url=' . $request['url'];
            $sign = sha1($str);

            error_log(date('Y-m-d H:i:s').' 微信接口生成签名:'.$sign . "\r\n",3,$log_file);

            return ['code'=>200,'data'=>['nonceStr'=>$noncestr,'timestamp'=>$time,'signature'=>$sign,'appid'=>$request['appid']]];
        }else{
            return ['code'=>400,'message'=>'生成ticket失败'];
        }
    }

    //获取jsapi_ticket
    function get_jsapi_ticket($appid){
        if(Redis::exists('ticket_' . $appid)){
            return Redis::get('ticket_' . $appid);
        }else{
            $access_token = $this->get_access_token($appid);
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
            $jsapi_ticket = curl_get($url);
            $jsapi_ticket = json_decode($jsapi_ticket,1);

            if($jsapi_ticket['errcode']){
                return false;
            }else{
                Redis::setex('ticket_' . $appid,7200,$jsapi_ticket['ticket']);
                return $jsapi_ticket['ticket'];
            }
        }
    }


    //通过open_id获取用户微信信息
    function get_userinfo_by_openid(Request $request){
        $log_file = base_path() . '/storage/logs/'.$request->post('appid').'.log';

        $validate = Validator::make($request->all(),[
            'appid' => 'required',
            'openid' => 'required'
        ]);
        if($validate->fails()){
            return ['code'=>400,'message'=>$validate->errors()->first()];
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$this->get_access_token($request['appid']).'&openid='.$request['openid'].'&lang=zh_CN';

        $userinfo = curl_get($url);

        error_log(date('Y-m-d H:i:s') . ' 通过openid获取用户信息结果:' . $userinfo . "\r\n",3,$log_file);

        $userinfo = json_decode($userinfo,1);
        if(isset($userinfo['errcode'])){
            return ['code'=>400,'message'=>$userinfo['errmsg']];
        }

        $userinfo = ['code' => 200, 'data' => $userinfo];
        return $userinfo;
    }





}
